package dongze.com.ckdj.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.inject.Inject;

import butterknife.ButterKnife;
import butterknife.OnClick;
import dongze.com.ckdj.R;
import dongze.com.ckdj.dagger.component.VehicleComponent;
import dongze.com.ckdj.data.entity.response.NamePlate;
import dongze.com.ckdj.data.entity.response.User;
import dongze.com.ckdj.data.entity.response.VehicleInformationDetail;
import dongze.com.ckdj.databinding.FragmentNamePlateBinding;
import dongze.com.ckdj.databinding.model.NamePlateModel;
import dongze.com.ckdj.persistence.DaoHelper;
import dongze.com.ckdj.persistence.dao.DaoSession;
import dongze.com.ckdj.service.IImageUploadService;
import dongze.com.ckdj.service.ImageUploadService;
import dongze.com.ckdj.util.MyLog;
import dongze.com.ckdj.util.Util;
import io.reactivex.observers.DisposableObserver;


import static android.content.Context.BIND_AUTO_CREATE;

/**
 * Created by fanqwz on 2017/8/11.
 */

public class NamePlateFragment extends ProcessableFragment {
    private static final String TAG = NamePlateFragment.class.getSimpleName();
    private static final int PHOTO_INTENT = 1234;
    private static final String IMAGE_PRIFIX = "nameplate";
    private File imageFile;
    private int degree = 0;
    private NamePlateModel namePlateModel = new NamePlateModel();
    private OnNamePlateOKListener listener;
    @Inject
    User user;
    @Inject
    VehicleInformationDetail vehicleInformationDetail;
    @Inject
    DaoSession daoSession;
    IImageUploadService mService;

    ServiceConnection mConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MyLog.d(TAG, "onServiceConnected: ");
            mService = IImageUploadService.Stub.asInterface(service);
//            try {
//                mService.addCallback(mBinder);
//            } catch (RemoteException e) {
//                e.printStackTrace();
//            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            MyLog.d(TAG, "onServiceDisconnected: ");
//            try {
//                mService.removeCallback(mBinder);
//            } catch (RemoteException e) {
//                e.printStackTrace();
//            }
            mService = null;
        }
    };

    public void setData(String vin, User user, DaoSession daoSession) {
        MyLog.v(TAG, "setData:" + vin + ":" + user.getUser_no());
        vehicleInformationDetail = new VehicleInformationDetail();
        vehicleInformationDetail.setVin(vin);
        this.user = user;
        this.daoSession = daoSession;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getContext().bindService(new Intent(this.getContext(), ImageUploadService.class), mConn, BIND_AUTO_CREATE);

        if (getComponent(VehicleComponent.class) != null && vehicleInformationDetail == null) {
            getComponent(VehicleComponent.class).inject(this);
            MyLog.v(TAG, "onCreate: inject vehicle component");
            MyLog.v(TAG, "onCreate: vehicleInformationDetail.vin=" + vehicleInformationDetail == null ? "null" : vehicleInformationDetail.getVin());
        }

        if (vehicleInformationDetail != null)
            queryNamePlate(vehicleInformationDetail.getVin());
        else {
            new AlertDialog.Builder(getActivity())
                    .setMessage("没有车架号")
                    .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            getFragmentManager().beginTransaction()
                                    .remove(NamePlateFragment.this)
                                    .commitAllowingStateLoss();
                        }
                    });
        }
    }

    @Nullable
    @Override
    public View createContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        FragmentNamePlateBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_name_plate, container, false);
        binding.setNamePlat(namePlateModel);
        ButterKnife.bind(this, binding.getRoot());
        return binding.getRoot();
    }

    @Override
    public void onDestroy() {
        if (imageFile != null && imageFile.exists())
            imageFile.delete();

        getContext().unbindService(mConn);
        super.onDestroy();
    }

    private void queryNamePlate(String vin) {
        mapUtil.getNamePlate(vin, new DisposableObserver<NamePlate>() {
            @Override
            protected void onStart() {
                MyLog.d(TAG, "onStart: ");
                super.onStart();
                doProcessing();
            }

            @Override
            public void onNext(NamePlate value) {
                MyLog.d(TAG, "onNext: ");
                if (value != null && value.getImg() != null && !value.getImg().isEmpty()) {
                    Toast toast = new Toast(getActivity());
                    toast.setDuration(Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    TextView textView = new TextView(getActivity());
                    textView.setTextSize(getResources().getDimension(R.dimen.center_toast_size));
                    textView.setText("铭牌图片已上传，无需再次录入");
                    textView.setBackgroundColor(0xFF000000);
                    textView.setTextColor(0xFFFFFFFF);
                    toast.setView(textView);
                    toast.show();
//                    listener.onOutLineOK(value.getImg());
                }
            }

            @Override
            public void onError(Throwable e) {
                MyLog.e(TAG, "onError: ", e);
                new AlertDialog.Builder(getActivity())
                        .setMessage(e.getMessage())
                        .create()
                        .show();
                finishProcessing();
            }

            @Override
            public void onComplete() {
                finishProcessing();
            }
        });
    }

    public void setListener(OnNamePlateOKListener listener) {
        this.listener = listener;
    }

    @OnClick({R.id.btn_recapture, R.id.btn_capture})
    public void onClick(View view) {
        if (!Util.checkCapturePermission(getActivity())) {
            return;
        }

        if (imageFile != null && imageFile.exists())
            Util.deleteFile(imageFile.getAbsolutePath());

        imageFile = Util.getImageFile(IMAGE_PRIFIX);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion < 24) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
            startActivityForResult(intent, PHOTO_INTENT);
        } else {
            Uri uri = FileProvider.getUriForFile(getActivity(), "dongze.com.ckdj.fileprovider", imageFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivityForResult(intent, PHOTO_INTENT);
        }
    }

    @OnClick(R.id.btn_upload)
    public void upload(View view) {
        if (imageFile != null && imageFile.exists()) {
//            uploadNamePlateToService();
            uploadNamePlate(imageFile);
        } else {
            new AlertDialog.Builder(getContext())
                    .setTitle("错误")
                    .setMessage("图片不存在，请重新拍摄！")
                    .create()
                    .show();
        }
    }

    @OnClick(R.id.rotate_left)
    public void rotateLeft() {
        try {
            ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_UNDEFINED:
                    exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_ROTATE_270));
                    degree = 270;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_ROTATE_180));
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_ROTATE_90));
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_UNDEFINED));
                    degree = 0;
                    break;
            }
            exif.saveAttributes();
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inSampleSize = 2;
            Bitmap b = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), o);
            Matrix matrix = new Matrix();
            matrix.setRotate(degree);
            b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);
            namePlateModel.img.set(new BitmapDrawable(getResources(), b));
//            namePlateModel.img.set(imageFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.rotate_right)
    public void rotateRight() {
        try {
            ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_UNDEFINED:
                    exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_ROTATE_90));
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_ROTATE_180));
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_ROTATE_270));
                    degree = 270;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_UNDEFINED));
                    degree = 0;
                    break;
            }
            exif.saveAttributes();
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inSampleSize = 2;
            Bitmap b = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), o);
            Matrix matrix = new Matrix();
            matrix.setRotate(degree);
            b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);
            namePlateModel.img.set(new BitmapDrawable(getResources(), b));
//            namePlateModel.img.set(imageFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void uploadNamePlateToService(File image) {
        try {
            Date time = new Date();
            mService.addTask(DaoHelper.createNamePlateTask(daoSession,
                    vehicleInformationDetail.getVin(),
                    user.getUser_no(),
                    "img",
                    image.getAbsolutePath(),
                    time));
            MyLog.i(TAG, "uploadNamePlateToService: vin:" + vehicleInformationDetail.getVin() + " username:" + user.getUser_name() + " path:" + image.getAbsolutePath());
            new AlertDialog.Builder(getContext())
                    .setTitle("成功")
                    .setMessage("图片已加入到离线上传列表，请去点击上传！")
                    .create()
                    .show();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 同步上传铭牌
     */
    private void uploadNamePlate(final File image) {
        mapUtil.uploadImage(image, new DisposableObserver<String>() {
            @Override
            protected void onStart() {
                super.onStart();
                doProcessing();
            }

            @Override
            public void onNext(String value) {
                commitNamePlate(vehicleInformationDetail.getVin(), value, image.getAbsolutePath());
            }

            @Override
            public void onError(Throwable e) {
                MyLog.e(TAG, "onError: ", e);
                new AlertDialog.Builder(getActivity())
                        .setTitle("错误")
                        .setMessage("上传图片失败" + e.getMessage())
                        .create()
                        .show();
                finishProcessing();
            }

            @Override
            public void onComplete() {
                finishProcessing();
            }
        });
    }

    private void commitNamePlate(final String vehicleNumber, String imageRet, final String filepath) {
        mapUtil.uploadNamePlate(vehicleNumber, "img", imageRet, user.getUser_no(), new DisposableObserver<String>() {
            @Override
            protected void onStart() {
                super.onStart();
                doProcessing();
            }

            @Override
            public void onNext(String value) {
                listener.onNamePalteOK(value);
            }

            @Override
            public void onError(Throwable e) {
                MyLog.e(TAG, "onError: ", e);
                new AlertDialog.Builder(getActivity())
                        .setTitle("错误")
                        .setMessage("更新铭牌失败:" + e.getMessage())
                        .create()
                        .show();
                finishProcessing();
            }

            @Override
            public void onComplete() {
                namePlateModel.img.set(null);
                Util.deleteFile(filepath);
                finishProcessing();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_INTENT && resultCode == Activity.RESULT_OK && imageFile != null && imageFile.exists()) {
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inSampleSize = 2;
            Bitmap b = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), o);
            namePlateModel.img.set(new BitmapDrawable(getResources(), b));
//            namePlateModel.img.set(imageFile.getAbsolutePath());
            namePlateModel.view.set(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (imageFile != null)
                        Util.ViewImage(getActivity(), imageFile);
                }
            });
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    public interface OnNamePlateOKListener {
        void onNamePalteOK(String uri);
    }
}
